@extends('dashboard.includes.master')

@section('title', 'Email Report')

@section('css')
<style>
.sort-icon {
    cursor: pointer;
    margin-left: 5px;
}

.sort-asc::after {
    content: '↑';
}

.sort-desc::after {
    content: '↓';
}

.sort-none::after {
    content: '↕';
}

th.sortable {
    cursor: pointer;
    user-select: none;
}

.loader {
    display: none;
    position: absolute;
    right: 45px;
    top: 10px;
    border: 3px solid #f3f3f3;
    border-radius: 50%;
    border-top: 3px solid #3498db;
    width: 20px;
    height: 20px;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.search-container {
    position: relative;
}

.search-info {
    margin-bottom: 15px;
    font-size: 0.9rem;
    color: #6c757d;
}

.search-results {
    display: none;
    background-color: #f8f9fa;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 15px;
}
</style>
@endsection

@section('content')
<div class="container mt-4">
    <h2 class="mb-4 text-center">Email Sending Report</h2>

    <!-- Statistics Section -->
    <div class="row text-center mb-4" id="stats-cards">
        <div class="col-md-4">
            <div class="card text-white bg-success">
                <div class="card-body">
                    <h5 class="card-title">Sent Messages</h5>
                    <p class="card-text fs-2" id="sent-count">{{ $sent }}</p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-white bg-warning">
                <div class="card-body">
                    <h5 class="card-title">Pending Messages</h5>
                    <p class="card-text fs-2" id="pending-count">{{ $pending }}</p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-white bg-danger">
                <div class="card-body">
                    <h5 class="card-title">Failed Messages</h5>
                    <p class="card-text fs-2" id="failed-count">{{ $failed }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Search Form and Messages Table -->
    <div class="mb-3 search-container">
        <div class="input-group">
            <input type="text" id="searchInput" name="search" class="form-control" placeholder="Search across all emails..."
                value="{{ request('search') }}">
            <button type="button" id="clearSearch" class="btn btn-outline-secondary">
                <i class="fa fa-times"></i>
            </button>
            <div class="loader" id="searchLoader"></div>
        </div>
    </div>
    
    <!-- Search Results Info -->
    <div class="search-results" id="searchResultsInfo">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                Showing <span id="filteredCount">0</span> results from <span id="totalCount">{{ $total_records ?? 0 }}</span> total records
            </div>
            <div>
                <button id="resetSearch" class="btn btn-sm btn-outline-secondary">Show All Records</button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table id="file-export" class="table table-bordered text-nowrap w-100">
            <thead class="table-dark">
                <tr>
                    <th>#</th>
                    <th class="sortable" data-sort="sender_name">Sender Name <span class="sort-icon sort-none"></span></th>
                    <th class="sortable" data-sort="sender_email">Sender Email <span class="sort-icon sort-none"></span></th>
                    <th class="sortable" data-sort="receiver_email">Receiver Email <span class="sort-icon sort-none"></span></th>
                    <th class="sortable" data-sort="subject">Subject <span class="sort-icon sort-none"></span></th>
                    <th class="sortable" data-sort="send_at">Send At <span class="sort-icon sort-desc"></span></th>
                    <th class="sortable" data-sort="status">Status <span class="sort-icon sort-none"></span></th>
                </tr>
            </thead>
            <tbody id="table-body">
                @foreach($messages as $index => $message)
                    <tr>
                        <td>{{ ($messages->currentPage() - 1) * $messages->perPage() + $index + 1 }}</td>
                        <td>{{ $message->sender[0]->name ?? '-' }}</td>
                        <td>{{ $message->sender[0]->email ?? '-' }}</td>
                        <td>{{ $message->reciever[0]->email ?? '-' }}</td>
                        <td>{{ $message->subject }}</td>
                        <td>{{ \Carbon\Carbon::parse($message->send_at)->format('Y-m-d H:i') }}</td>
                        <td>
                            @if ($message->status == 'sent')
                                <span class="badge bg-success">Sent</span>
                            @elseif ($message->status == 'pending')
                                <span class="badge bg-warning">Pending</span>
                            @else
                                <span class="badge bg-danger">Failed</span>
                            @endif
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
    
    <div class="d-flex justify-content-center mt-3" id="pagination-container">
        {{ $messages->links('pagination::bootstrap-5') }}
    </div>
</div>
@endsection

@section('js')
<script>
document.addEventListener("DOMContentLoaded", function() {
    const tableBody = document.getElementById('table-body');
    const searchInput = document.getElementById('searchInput');
    const searchLoader = document.getElementById('searchLoader');
    const clearSearchBtn = document.getElementById('clearSearch');
    const resetSearchBtn = document.getElementById('resetSearch');
    const paginationContainer = document.getElementById('pagination-container');
    const sentCount = document.getElementById('sent-count');
    const pendingCount = document.getElementById('pending-count');
    const failedCount = document.getElementById('failed-count');
    const searchResultsInfo = document.getElementById('searchResultsInfo');
    const filteredCount = document.getElementById('filteredCount');
    const totalCount = document.getElementById('totalCount');
    
    let currentSortColumn = 'send_at';
    let currentSortOrder = 'desc';
    let typingTimer;
    const doneTypingInterval = 500; // Time in ms (0.5 seconds)

    // Search functionality
    searchInput.addEventListener('input', function() {
        const query = this.value.trim();
        
        // Clear previous timer
        clearTimeout(typingTimer);
        
        // Show loader
        searchLoader.style.display = 'block';
        
        // Set new timer
        typingTimer = setTimeout(() => {
            fetchSearchResults(query);
        }, doneTypingInterval);
    });

    // Clear search button
    clearSearchBtn.addEventListener('click', function() {
        searchInput.value = '';
        fetchSearchResults('');
    });
    
    // Reset search button
    resetSearchBtn.addEventListener('click', function() {
        searchInput.value = '';
        fetchSearchResults('');
    });

    // Fetch search results function
    function fetchSearchResults(query) {
        fetch(/messages/search?search=${query})
            .then(response => response.json())
            .then(data => {
                // Hide loader
                searchLoader.style.display = 'none';
                
                // Update table body with search results
                tableBody.innerHTML = data.rows;
                
                // Update pagination
                paginationContainer.innerHTML = data.pagination;
                
                // Update stats cards
                sentCount.textContent = data.stats.sent;
                pendingCount.textContent = data.stats.pending;
                failedCount.textContent = data.stats.failed;
                
                // Update search results info
                filteredCount.textContent = data.filtered_records;
                totalCount.textContent = data.total_records;
                
                // Show or hide search results info based on if we're filtering
                if (query && data.filtered_records !== data.total_records) {
                    searchResultsInfo.style.display = 'block';
                } else {
                    searchResultsInfo.style.display = 'none';
                }
                
                // Re-apply sorting if needed
                sortTable(currentSortColumn, currentSortOrder);
                
                // Add event listeners to the new pagination links
                attachPaginationEventListeners();
            })
            .catch(error => {
                console.error('Error fetching search results:', error);
                searchLoader.style.display = 'none';
            });
    }

    // Attach event listeners to pagination links
    function attachPaginationEventListeners() {
        const paginationLinks = document.querySelectorAll('.pagination a');
        
        paginationLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                
                const url = new URL(this.href);
                const page = url.searchParams.get('page');
                const searchTerm = searchInput.value.trim();
                
                // Show loader
                searchLoader.style.display = 'block';
                
                // Fetch data for the selected page
                fetch(/messages/search?search=${searchTerm}&page=${page})
                    .then(response => response.json())
                    .then(data => {
                        // Hide loader
                        searchLoader.style.display = 'none';
                        
                        // Update table body with search results
                        tableBody.innerHTML = data.rows;
                        
                        // Update pagination
                        paginationContainer.innerHTML = data.pagination;
                        
                        // Update stats cards
                        sentCount.textContent = data.stats.sent;
                        pendingCount.textContent = data.stats.pending;
                        failedCount.textContent = data.stats.failed;
                        
                        // Update search results info
                        filteredCount.textContent = data.filtered_records;
                        totalCount.textContent = data.total_records;
                        
                        // Re-apply sorting if needed
                        sortTable(currentSortColumn, currentSortOrder);
                        
                        // Re-attach event listeners to the new pagination links
                        attachPaginationEventListeners();
                    })
                    .catch(error => {
                        console.error('Error fetching page data:', error);
                        searchLoader.style.display = 'none';
                    });
            });
        });
    }

    // Sort table function
       function sortTable(column, order) {
        const rows = Array.from(tableBody.querySelectorAll('tr'));

        rows.sort((a, b) => {
            const cellA = a.querySelector(`td:nth-child(${getColumnIndex(column)})`)?.textContent.trim().toLowerCase() || '';
            const cellB = b.querySelector(`td:nth-child(${getColumnIndex(column)})`)?.textContent.trim().toLowerCase() || '';

            if (order === 'asc') {
                return cellA.localeCompare(cellB, undefined, { numeric: true });
            } else {
                return cellB.localeCompare(cellA, undefined, { numeric: true });
            }
        });

        rows.forEach(row => tableBody.appendChild(row));
        updateSortIcons(column, order);
    }

    function getColumnIndex(column) {
        switch (column) {
            case 'sender_name': return 2;
            case 'sender_email': return 3;
            case 'receiver_email': return 4;
            case 'subject': return 5;
            case 'send_at': return 6;
            case 'status': return 7;
            default: return 1;
        }
    }

    function updateSortIcons(column, order) {
        document.querySelectorAll('th.sortable').forEach(th => {
            const icon = th.querySelector('.sort-icon');
            if (th.dataset.sort === column) {
                icon.classList.remove('sort-none', 'sort-asc', 'sort-desc');
                icon.classList.add(order === 'asc' ? 'sort-asc' : 'sort-desc');
            } else {
                icon.classList.remove('sort-asc', 'sort-desc');
                icon.classList.add('sort-none');
            }
        });
    }

    // Click event on sortable headers
    document.querySelectorAll('th.sortable').forEach(th => {
        th.addEventListener('click', function() {
            const column = this.dataset.sort;
            let newOrder = 'asc';
            if (currentSortColumn === column && currentSortOrder === 'asc') {
                newOrder = 'desc';
            }
            currentSortColumn = column;
            currentSortOrder = newOrder;
            sortTable(column, newOrder);
        });
    });

    // Initial sort
    sortTable(currentSortColumn, currentSortOrder);
});
</script>
@endsection
